import { Component, OnInit, Input } from '@angular/core'
import { Widget } from '../../model'
import { JsonApiService } from '../../../../core/api/json-api.service'

declare const echarts: any
declare const layui: any
declare const $: any
let chart = null

@Component({
  selector: 'install-car-map',
  templateUrl: './install-car-map.html',
  styleUrls: ['./install-car-map.css']
})
export class InstallCarMapComponent implements OnInit, Widget {
  @Input() componentData: any

  chartOption = {
    backgroundColor: 'transparent',
    title: {
      text: '',
      x: 24,
      top: 12,
      textStyle: {
        fontSize: 14,
        fontWeight: 'bold'
      }
    },
    tooltip: {
      show: false
    },
    geo: {
      map: 'china',
      roam: true,
      zoom: 1.2,
      label: {
        normal: {
          show: true,
          textStyle: {
            color: '#333'
          }
        }
      },
      itemStyle: {
        normal: {
          borderColor: '#666'
        }
      },
      emphasis: {
        itemStyle: {
          color: '#eeeeee'
        }
      }
    },
    series: [
      {
        name: '车辆',
        type: 'effectScatter',
        coordinateSystem: 'geo',
        symbolSize: 12,
        legendHoverLink: false,
        label: {
          normal: {
            show: false
          },
          emphasis: {
            show: false
          }
        },
        itemStyle: {
          normal: {
            color: '#408df5',
            shadowBlur: 5,
            shadowColor: '#a3c3f9'
          }
        }
      }
    ]
  }

  geoCoordMap = {
    北京: [116.39737, 39.939502],
    天津: [117.133262, 39.256321],
    上海: [121.36464, 31.303465],
    重庆: [106.32485, 29.895013],
    河北: [114.336873, 38.21885],
    山西: [112.349964, 38.044464],
    辽宁: [123.241164, 41.948112],
    吉林: [125.228072, 43.894927],
    黑龙江: [126.479088, 45.985284],
    江苏: [118.775429, 32.046466],
    浙江: [120.040035, 30.350837],
    安徽: [117.170056, 31.99595],
    福建: [119.156964, 26.182279],
    江西: [115.808656, 28.774611],
    山东: [116.912494, 36.812038],
    河南: [113.453802, 34.895028],
    湖北: [114.116105, 30.764814],
    湖南: [112.800698, 28.474291],
    广东: [113.233035, 23.224606],
    海南: [110.179083, 19.921006],
    四川: [103.924003, 30.796585],
    贵州: [106.499624, 26.844365],
    云南: [102.599397, 25.248948],
    陕西: [108.780889, 34.408508],
    甘肃: [103.66644, 36.218003],
    青海: [101.605943, 36.752842],
    西藏自治区: [90.972306, 29.838888],
    广西壮族自治区: [108.265765, 23.020403],
    内蒙古自治区: [111.614073, 40.951504],
    宁夏回族自治区: [106.094884, 38.624116],
    新疆维吾尔自治区: [87.476819, 43.894927],
    香港特别行政区: [114.1529, 22.542716],
    澳门特别行政区: [113.417008, 22.337477],
    台湾: [121.36464, 25.248948]
  }

  left = 0 // 弹框定位left
  top = 0 // 弹框定位top
  headerData = {
    title: '',
    count: ''
  } // 弹框头部显示数据
  dialogShow = false // 弹框是否显示
  isMoveFlag = true // 节流，控制mousemove触发频率
  treeTable = null // 树形表格实例
  loading = false

  constructor(private jsonApiService: JsonApiService) {}
  ngOnInit() {}

  ngAfterViewInit() {
    setTimeout(() => {
      chart = echarts.init(document.getElementById('carMap'))
      this.setOptions(this.chartOption)
      this.setData()
      this.initTableTree()
      window.addEventListener('resize', this.resizeChart)
      window.addEventListener('mousemove', this.handleDialogIsClose.bind(this))
      // 监听鼠标移动事件
      // chart.on('click', params => {
      chart.on('mousemove', params => {
        if (params.seriesType !== 'effectScatter') return
        this.throttle(this.handleDialogData, 300)(params, this)
      })
      // 监听地图缩放或移动事件
      chart.on('georoam', params => {
        if (this.dialogShow) this.closeDialog()
      })
    })
  }

  ngOnDestroy() {
    if (!chart) return
    window.removeEventListener('resize', this.resizeChart)
    window.removeEventListener('mousemove', this.handleDialogIsClose.bind(this))
    chart.dispose()
    chart = null
  }

  resizeChart() {
    chart && chart.resize()
  }

  setOptions(option: any) {
    if (chart) {
      chart.setOption(option)
    }
  }

  setData() {
    this.loading = true
    this.jsonApiService.http('control/station/car/map/installCarMap.html', null, false).subscribe(result => {
      this.loading = false
      const carData = this.convertData(result.data)
      chart.setOption({
        series: [
          {
            data: carData
          }
        ]
      })
    })
  }

  // 整理车辆地图数据
  convertData(data) {
    const res = []
    for (let i = 0; i < data.length; i++) {
      const item = data[i]
      const geoCoord = this.geoCoordMap[item.name]
      if (geoCoord) {
        res.push({
          name: item.name,
          value: geoCoord,
          count: item.count,
          companyCar: item.children
        })
      }
    }
    return res
  }

  // 初始化表格树
  initTableTree() {
    const that = this
    layui.use(function () {
      that.treeTable = layui.treeTable
      that.treeTable.render({
        elem: '#carTreeTable',
        data: [],
        maxHeight: '300px',
        skin: 'nob',
        size: 'sm',
        tree: {
          view: {
            showIcon: false,
            dblClickExpand: false
          }
        },
        cols: [
          [
            { field: 'name', title: '', align: 'left', width: 220 },
            { field: 'count', title: '', align: 'left', width: 70 }
          ]
        ]
      })
      // 树形表格单击展开
      that.treeTable.on('row(carTreeTable)', data => {
        const expandFlag = !data.data.LAY_EXPAND
        const index = data.index
        that.treeTable.expandNode('carTreeTable', {
          index,
          expandFlag
        })
      })
    })
  }

  // 处理弹框数据
  handleDialogData(params: any, that) {
    that.dialogShow = true

    const event = params.event.event
    that.calcDialogPosition(event, that)

    const dialogData = params.data
    that.headerData.title = dialogData.name
    that.headerData.count = dialogData.count
    that.treeTable.reloadData('carTreeTable', { data: dialogData.companyCar })
  }

  //点击其他区域关闭弹框
  handleDialogIsClose(e: any) {
    const dialogEl = document.getElementById('carDialog')
    if (dialogEl && !dialogEl.contains(e.target)) {
      const tipsDialogEl = document.getElementsByClassName('layui-table-tips')[0]
      if (tipsDialogEl && tipsDialogEl.contains(e.target)) return
      this.closeDialog()
    }
  }

  // 关闭弹框
  closeDialog() {
    this.dialogShow = false
  }

  // 节流
  throttle(fn: (...args: any[]) => void, delay = 300) {
    let timer: any = null
    return function (this: any, ...args: any[]) {
      if (timer) {
        return
      }
      timer = setTimeout(() => {
        timer = null
        fn.apply(this, args)
      }, delay)
    }
  }

  // 计算弹框定位
  calcDialogPosition(event, that) {
    const dialogEl = document.getElementById('carDialog')
    const dialogWidth = dialogEl.offsetWidth // 获取弹框宽度
    const dialogHeight = dialogEl.offsetHeight // 获取弹框高度
    const clientWidth = window.innerWidth // 获取窗口宽度
    const clientHeight = window.innerHeight // 获取窗口宽度
    const offsetX = 20 // 弹框X轴偏移量
    const offsetY = 5 // 弹框Y轴偏移量

    if (event.clientX + dialogWidth > clientWidth) {
      that.left = event.clientX - dialogWidth + offsetX
      $('.arrows').addClass('arrows-right')
      $('.arrows').removeClass('arrows-left')
    } else {
      that.left = event.clientX - offsetX
      $('.arrows').addClass('arrows-left')
      $('.arrows').removeClass('arrows-right')
    }

    if (event.clientY + dialogHeight > clientHeight) {
      that.top = event.clientY - dialogHeight - offsetY
      $('.arrows').addClass('arrows-bottom')
      $('.arrows').removeClass('arrows-top')
      $('.arrows').addClass('arrows-down')
      $('.arrows').removeClass('arrows-up')
    } else {
      that.top = event.clientY + offsetY
      $('.arrows').addClass('arrows-top')
      $('.arrows').removeClass('arrows-bottom')
      $('.arrows').addClass('arrows-up')
      $('.arrows').removeClass('arrows-down')
    }

    // that.left = event.clientX - 20
    // that.top = event.clientY + 5
  }
}
